package org.lee.sc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Server
 * 服务器
 *
 * @author dralee
 * @date 2021-12-28 18:06:38
 **/
public class Server {
    public static void main(String[] args) {
        int port = 12321;
        try (ServerSocket listener = new ServerSocket(port)) {
            System.out.printf("Server is listening on port %d%n", port);
            while (true) {
                try (Socket client = listener.accept()) {
                    System.out.printf("client(%s:%d) connected%n", client.getInetAddress().toString(), client.getPort());
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
                        try (PrintWriter writer = new PrintWriter(client.getOutputStream(), true)) {
                            String line;
                            do {
                                if (null != (line = reader.readLine())) {
                                    writer.printf("Server: %s%n", new StringBuilder(line).reverse());
                                    System.out.printf("received: %s%n", line);
                                }
                            } while (!"byte".equals(line) && !"quit".equals(line));
                            System.out.printf("client(%s:%d) disconnected%n", client.getInetAddress().toString(), client.getPort());
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
